<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button type="primary" @click="handleAdd">添加分类</el-button>
    </div>
    
    <el-table
      v-loading="loading"
      :data="categoryList"
      border
      style="width: 100%"
      row-key="categoryId"
    >
      <el-table-column prop="categoryId" label="ID" width="80" align="center" />
      <el-table-column prop="categoryName" label="分类名称" min-width="150" />
      <el-table-column prop="orderNum" label="排序" width="100" align="center" />
      <el-table-column label="操作" width="200" align="center">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 分类表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="categoryName">
          <el-input v-model="form.categoryName" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="排序" prop="orderNum">
          <el-input-number v-model="form.orderNum" :min="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="submitForm">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getCategoryPage, getCategoryList, saveOrUpdateCategory, deleteCategory } from '@/api/category'

// 分类列表
const categoryList = ref([])
// 总数据量
const total = ref(0)
// 加载状态
const loading = ref(false)
// 提交加载状态
const submitLoading = ref(false)
// 表单对话框可见状态
const dialogVisible = ref(false)
// 表单对话框标题
const dialogTitle = ref('添加分类')
// 表单引用
const formRef = ref(null)

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10
})

// 表单数据
const form = reactive({
  categoryId: null,
  categoryName: '',
  orderNum: 0
})

// 表单验证规则
const rules = {
  categoryName: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  orderNum: [
    { required: true, message: '请输入排序', trigger: 'blur' }
  ]
}

// 初始化数据
onMounted(async () => {
  await fetchData()
})

// 获取分类列表数据
const fetchData = async () => {
  loading.value = true
  try {
    const res = await getCategoryPage(queryParams)
    categoryList.value = res.data.list || []
    total.value = res.data.total || 0
  } catch (error) {
    console.error('获取分类列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 处理页码变化
const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  fetchData()
}

// 处理每页条数变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  queryParams.pageNum = 1
  fetchData()
}

// 处理添加分类
const handleAdd = () => {
  dialogTitle.value = '添加分类'
  resetForm()
  dialogVisible.value = true
}

// 处理编辑分类
const handleEdit = (row) => {
  dialogTitle.value = '编辑分类'
  resetForm()
  Object.assign(form, row)
  dialogVisible.value = true
}

// 处理删除分类
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确认删除分类 "${row.categoryName}" 吗？`,
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteCategory(row.categoryId)
      ElMessage({
        type: 'success',
        message: '删除成功!'
      })
      await fetchData()
    } catch (error) {
      console.error('删除分类失败:', error)
    }
  }).catch(() => {
    // 取消删除
  })
}

// 重置表单
const resetForm = () => {
  form.categoryId = null
  form.categoryName = ''
  form.orderNum = 0
  
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 提交表单
const submitForm = () => {
  formRef.value.validate(async valid => {
    if (!valid) return
    
    submitLoading.value = true
    try {
      await saveOrUpdateCategory(form)
      ElMessage({
        type: 'success',
        message: form.categoryId ? '更新成功!' : '添加成功!'
      })
      dialogVisible.value = false
      await fetchData()
    } catch (error) {
      console.error('保存分类失败:', error)
    } finally {
      submitLoading.value = false
    }
  })
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.filter-container {
  padding-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  text-align: right;
}
</style> 